package com.example.studentregistration.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.studentregistration.mapper.DormBuildingMapper;
import com.example.studentregistration.mapper.DormRoomMapper;
import com.example.studentregistration.pojo.DormBuilding;
import com.example.studentregistration.pojo.DormRoom;
import com.example.studentregistration.service.DormRoomService;
import com.example.studentregistration.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Service
public class DormRoomServiceImpl implements DormRoomService {

    @Autowired
    private DormRoomMapper dormRoomMapper;
    @Autowired
    private DormBuildingMapper dormBuildingMapper;

    @Override
    public Result<?> insert(DormRoom room) {
        // 校验楼宇存在
        DormBuilding building = dormBuildingMapper.findById(room.getBuildingId());
        if (building == null) return Result.fail("所属楼宇不存在");
        // 唯一：同楼宇房间号唯一
        DormRoom exists = dormRoomMapper.findByBuildingAndRoomNo(room.getBuildingId(), room.getRoomNo());
        if (exists != null) return Result.fail("该楼宇下房间号已存在");
        if (room.getOccupiedCount() == null) room.setOccupiedCount(0);

        System.out.println("=== 开始办理入住 ===");
        System.out.println(room);

        int res = dormRoomMapper.insert(room);
        if (res > 0) {
            // 同步更新楼宇统计
            building.setTotalRooms((building.getTotalRooms() == null ? 0 : building.getTotalRooms()) + 1);
            building.setTotalBeds((building.getTotalBeds() == null ? 0 : building.getTotalBeds()) + (room.getBedCount() == null ? 0 : room.getBedCount()));
            dormBuildingMapper.update(building);
            return Result.success("添加成功");
        }
        return Result.fail("添加失败");
    }

    @Override
    public Result<?> update(DormRoom room) {
        int res = dormRoomMapper.update(room);
        return res > 0 ? Result.success("修改成功") : Result.fail("修改失败");
    }

    @Override
    public Result<?> delete(Integer id) {
        int res = dormRoomMapper.delete(id);
        return res > 0 ? Result.success("删除成功") : Result.fail("删除失败");
    }

    @Override
    public int batchDelete(List<Integer> ids) {
        return dormRoomMapper.batchDelete(ids);
    }

    @Override
    public Page queryAll(Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        return (Page) dormRoomMapper.findAll();
    }

    @Override
    public Result<DormRoom> queryById(Integer id) {
        DormRoom room = dormRoomMapper.findById(id);
        return room != null ? Result.success(room) : Result.fail("未找到");
    }

    @Override
    public Result<List<DormRoom>> queryByBuildingId(Integer buildingId) {
        List<DormRoom> list = dormRoomMapper.findByBuildingId(buildingId);
        return Result.success(list);
    }

    // 新增：导出Excel
    @Override
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<DormRoom> list = dormRoomMapper.findAll();
        ExcelWriter writer = ExcelUtil.getWriter();
        writer.write(list, true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("宿舍房间信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream os = response.getOutputStream();
        writer.flush(os, true);
        writer.close();
        IoUtil.close(os);
    }
}